#include "mythread.h"
#include <stdio.h>

#define cfifo_path  "/home/debian/tmp/cfifo"
#define qfifo_path  "/home/debian/tmp/qfifo"
#define pro_path    "/home/debian/tftp_dir/gate"

int flag;

Mythread::Mythread(QObject *parent)
{
//    //创建子进程 运行控制程序
//    if( access(pro_path, F_OK) != 0 ){
//        printf("/home/debian/tftp_dir/gate is empty\n");
//        exit(-1);
//    }
//    pid_t pid;
//    pid = fork();
//    if( pid == 0 ){
//        ret = execl(pro_path, " ", NULL);
//        if( ret == -1 ){
//            printf("pro_path create error!\n");
//            exit(-1);
//        }
//    }
}

void Mythread::qt_send(char data)
{
    write(fifo_c, &data, 1);
//    if( write(fifo_c, &data, 1) != 1 ){
//        if( write(fifo_c, &data, 1) != 1 ){
//            printf("write to fifo_c error!\n");
//            exit(-1);
//        }
//    }
}

void Mythread::run()
{
//     printf("123123123123\n");
    if( access(cfifo_path, F_OK) != 0 ){
        ret = mkfifo(cfifo_path, 0777 );
        if( ret < 0 )
            printf("qt FIFO file creat error!\n");
    }
//    printf("123123123123\n");
    fifo_c = open(cfifo_path, O_RDWR | O_NONBLOCK);
    if( fifo_c < 0 ){
        printf("qt fifo_c file open error!\n");
        exit(-1);
    }
//    printf("123123123123\n");
    if( access(qfifo_path, F_OK) != 0 ){
        ret = mkfifo(qfifo_path, 0777 );
        if( ret < 0 )
            printf("qt qfifo_path file creat error!\n");
    }
//    printf("123123123123\n");
    fifo_q = open(qfifo_path, O_RDONLY | O_NONBLOCK);
    if( fifo_q < 0 ){
        printf("qt qfifo_path file open error!\n");
        exit(-1);
    }
//    printf("123123123123\n");
    while(1){
//        printf("1111111111\n");
        ret = read(fifo_q, &r_data, 1);
        if( ret > 0 ){
//            printf("66666666666\n");
            if( r_data == '1' ){
//                printf("77777777777\n");
                emit task_signal();
                QThread::msleep(500);
            }
        }
        printf("in run flag = %d\n",flag);
        if( flag == 1 ){
            if(write(fifo_c, "1", 1) != 1){
                printf("write fifo c error\n");
            }
             printf("222222222222\n");
             flag = 0;
        }
        if( flag == 2 ){
            if(write(fifo_c, "0", 1)!=1)
                    printf("write fifo c error\n");
            printf("44444444444\n");
            flag = 0;
        }

        printf("333333333333\n");
        QThread::msleep(300);
    }
}





